package com.pdd.mall.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pdd.mall.common.api.CommonResult;
import com.pdd.mall.dto.ReviewParam;
import com.pdd.mall.entity.Review;
import com.pdd.mall.entity.User;
import com.pdd.mall.service.ReviewService;
import com.pdd.mall.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * 评价控制器
 */
@RestController
@RequestMapping("/user/reviews")
public class ReviewController {

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private UserService userService;

    /**
     * 添加评价
     */
    @PostMapping
    public CommonResult<Review> addReview(@RequestBody @Valid ReviewParam param) {
        Long userId = getCurrentUserId();
        try {
            Review review = reviewService.addReview(param, userId);
            return CommonResult.success(review);
        } catch (IllegalArgumentException e) {
            return CommonResult.failed(e.getMessage());
        } catch (Exception e) {
            return CommonResult.failed("添加评价失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户评价列表
     */
    @GetMapping
    public CommonResult<Page<Review>> getUserReviews(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        Long userId = getCurrentUserId();
        Page<Review> reviewList = reviewService.getUserReviews(userId, pageNum, pageSize);
        return CommonResult.success(reviewList);
    }

    /**
     * 删除评价
     */
    @DeleteMapping("/{id}")
    public CommonResult<String> deleteReview(@PathVariable Long id) {
        Long userId = getCurrentUserId();
        boolean success = reviewService.deleteReview(id, userId);

        if (success) {
            return CommonResult.success("删除评价成功");
        } else {
            return CommonResult.failed("删除评价失败，评价不存在或不属于当前用户");
        }
    }

    /**
     * 检查订单是否已评价
     */
    @GetMapping("/check")
    public CommonResult<Boolean> checkReview(
            @RequestParam String orderNo,
            @RequestParam Long productId) {
        boolean reviewed = reviewService.isOrderReviewed(orderNo, productId);
        return CommonResult.success(reviewed);
    }

    /**
     * 获取订单评价
     */
    @GetMapping("/order")
    public CommonResult<Review> getOrderReview(
            @RequestParam String orderNo,
            @RequestParam Long productId) {
        Review review = reviewService.getOrderReview(orderNo, productId);
        // 即使评价不存在也返回成功，只是数据为null
        return CommonResult.success(review);
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        return user.getId();
    }
}
